package cn.jiedh.app.meiweidk.browse;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.NumUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;

/**
 * @name： 浏览记录
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/10/20
 * @modifyTime： 2017/10/20
 * @explain：
 */

public class BrowseActivity extends BaseActivity {
    @BindView(R.id.bar_img_back)
    ImageView barImgBack;
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.bar_tv_other)
    TextView barTvOther;
    @BindView(R.id.listview)
    EmptyRecyclerView listview;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    BaseAdapter<BrowseBean> adapter;
    List<BrowseBean> list = new ArrayList<>();
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;

    private View emptyview;

    @Override
    protected int getLayoutView() {
        return R.layout.act_browse;
    }

    @Override
    protected void initView(View view) {
        barTvTitle.setText("我的浏览");
        barTvOther.setVisibility(View.VISIBLE);
        barTvOther.setText("清空");
        statelayout.setOnNoClick(new StateLayout.NoNetView() {
            @Override
            public void setOnclck(View view) {
                smartrefreshLayout.autoRefresh();
            }
        });
        barTvOther.setTextColor(getResources().getColor(R.color.colorPrimary));
        listview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<BrowseBean>(this, R.layout.browse_item, list) {
            @Override
            public void convert(BaseViewHolder holder, BrowseBean browseBean, int position) {
                LinearLayout ll_title = holder.getView(R.id.ll_title);
                if (position == 0 || browseBean.isshowtitle()) {
                    ll_title.setVisibility(View.VISIBLE);
                    holder.setText(R.id.num, "共浏览了" + browseBean.getCount() + "个产品");
                } else {
                    ll_title.setVisibility(View.GONE);
                }
                holder.setText(R.id.time, browseBean.getBrowseTimeString());
                holder.setImageUrl(R.id.head, browseBean.getImgUrl());
                holder.setText(R.id.name, browseBean.getName());
                holder.setText(R.id.rost, NumUtils.getTwoDecimal(browseBean.getRate()) + "%");
                if (browseBean.getRateType() == 1) {  //月利率
                    holder.setText(R.id.tv_rate, "参考月利率");
                } else {   //日利率
                    holder.setText(R.id.tv_rate, "参考日利率");
                }
                int moneymin;
                int moneymax;
                String smin;
                String smax;
                if (browseBean.getMoneyMin() >= 100000) {
                    moneymin = ((int) browseBean.getMoneyMin()) / 10000;
                    smin = moneymin + "";
                } else {
                    moneymin = ((int) browseBean.getMoneyMin());
                    smin = moneymin + "";
                }
                if (browseBean.getMoneyMax() >= 100000) {
                    moneymax = ((int) browseBean.getMoneyMax()) / 10000;
                    smax = moneymax + "万";
                } else {
                    moneymax = ((int) browseBean.getMoneyMax());
                    smax = moneymax + "";
                }
                holder.setText(R.id.money, smin + "-" + smax);
                holder.setOnclickListener(R.id.browseitem, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MobclickAgent.onEvent(activity,"my_browse_product_click");
                        Bundle bundle = new Bundle();
                        bundle.putInt("productId", browseBean.getProductId());
                        bundle.putBoolean("fromeBrowse",true);
                        ActivityUtil.next(activity, LoanDetailActivity.class, bundle);
                        SPUtils.saveBuried("click", "0", browseBean.getName() + "", "",
                                 "我的浏览-列表", "", "", browseBean.getProductId() + "");
                    }
                });
            }
        };
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.setAdapter(adapter);
        smartrefreshLayout.autoRefresh();
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        smartrefreshLayout.setOnRefreshListener(refreshlayout -> refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                pageNo = 1;
                statelayout.netviewGone();
                getbrowselist();
                refreshlayout.finishRefresh();
            }
        }, 2000));

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void initData() {
        emptyview = findViewById(R.id.emptyview);
        emptyNnPic.setImageResource(R.mipmap.mylljl);
        emptyNnBtn.setText("暂无浏览记录");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.bar_img_back, R.id.bar_tv_other})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                finish();
                break;
            case R.id.bar_tv_other:
                if (list.size() == 0) {
                    T.showShort("暂无浏览记录");
                } else {
                    showdialog();
                }
                break;
        }
    }

    private void showdialog() {
        new AlertDialog(this).builder().setTitle("确定清空浏览历史?").setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearALL();
                MobclickAgent.onEvent(activity,"my_browse_clear_click");
                SPUtils.saveBuried("click", "0","我的浏览-浏览记录清空","","我的-我的浏览",
                        "","","");
            }
        }).show();
    }

    private int pageNo = 1;
    private int pageSize = 10;

    private void getbrowselist() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        request(this, UrlUtils.BROWSELIST, map, false, new ResponseSuccess<BrowseData>() {
            @Override
            public void onRequestSucceed(BaseResponse<BrowseData> response) {
                if (response.getCode() == 0) {
                    BrowseData browseData = response.getData();
                    if (browseData.getDataList() != null) {
                        List<BrowseBean> mlist = browseData.getDataList();
                        if (pageNo == 1) {
                            list.clear();
                            list.addAll(resetbrowsebean(mlist));
                        } else {
                            if (mlist.size() == 0) {
                                T.showShort("加载完成");
                            }
                            list.addAll(resetbrowsebean(mlist));
                        }
                    }
                }
                listview.setEmptyView(emptyview);
                adapter.notifyDataSetChanged();
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                statelayout.netviewGone();
                list.clear();
                listview.setEmptyView(emptyview);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 处理回来数据 这里最主要
     * @param mlist
     * @return
     */
    private List<BrowseBean> resetbrowsebean(List<BrowseBean> mlist) {//mlist是返回的所有浏览记录
        int theItem = 0;//展示条数数据的项
        if (mlist.size() == 0) {
            return mlist;
        } else {//处理mlist第一条数据
            mlist.get(theItem).setCount(1);//设置第一条数据
            if (list.size() > 0 && mlist.get(0).getBrowseTimeString().equals(list.get(list.size() - 1))) {//没用
                mlist.get(0).setIsshowtitle(false);
            } else {
                mlist.get(0).setIsshowtitle(true);
            }
        }
        for (int i = 1; i < mlist.size(); i++) {//处理mlist第一条之后的数据
            if (mlist.get(i).getBrowseTimeString().equals(mlist.get(i - 1).getBrowseTimeString())) {//相同
                mlist.get(i).setIsshowtitle(false);
                int count = mlist.get(theItem).getCount() + 1;
                mlist.get(theItem).setCount(count);
            } else {//不相同
                theItem = i;
                mlist.get(theItem).setCount(1);//设置第一条数据
                mlist.get(i).setIsshowtitle(true);
            }

        }
        return mlist;
    }

    /**
     * 清空
     */
    public void clearALL() {
        Map<String, Object> map = new HashMap<>();
        request(this, UrlUtils.CLEARALLBROWSE, map, false, new ResponseSuccess() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                if (response.getCode() == 0) {
                    list.clear();
                    listview.setEmptyView(emptyview);
                    adapter.notifyDataSetChanged();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
//                statelayout.netviewGone();
//                list.clear();
//                listview.setEmptyView(findViewById(R.id.emptyview));
//                adapter.notifyDataSetChanged();
            }
        });
    }
}
